/*
 * @Author: zxc
 * @Date: 2020-11-16 13:17:26
 * @LastEditTime: 2020-11-16 13:37:03
 * @LastEditors: zxc
 * @Description:最接近的三数之和
 */
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function (nums, target) {
  nums.sort((a, b) => a - b)
  let len = nums.length,
    sum,
    res = nums[0] + nums[1] + nums[2],
    L,
    R
  if (len === 3) return res
  for (var i = 0; i < len; i++) {
    if (nums[i] === nums[i - 1]) continue
    L = i + 1
    R = len - 1
    while (L < R) {
      sum = nums[i] + nums[L] + nums[R]
      if (Math.abs(res - target) > Math.abs(sum - target)) {
        res = sum
      }
      if (sum < target) L++
      else if (sum > target) R--
      else return res
    }
  }
  return res
}
